const requestURL = 'https://app.anfujia.info/api'
// const requestURL = 'http://192.168.2.151:9100'


function Request(url, data, method, timeout) {
	// #ifndef HELPER-PROD	
	// #endif  
	return new Promise((resolve, reject) => {
		uni.showLoading({
			mask: true
		})
		let lang = ''
		if (uni.getStorageSync('Lang') == 'zh-Hans') {
			lang = 'zh-CN'
		} else if (uni.getStorageSync('Lang') == 'zh-Hant') {
			lang = 'zh-HK'
		} else if (uni.getStorageSync('Lang') == 'en') {
			lang = 'en-US'
		} else {
			lang = 'zh-CN'
		}

		uni.request({
			url: requestURL + url,
			timeout: timeout,
			method: method,
			header: {
				'content-type': 'application/json',
				'Accept': 'application/json, text/javascript, */*; q=0.01',
				'Authorization': uni.getStorageSync('token'),
				'Lang': lang
			},
			data: data,
			success: (res) => {
				uni.hideLoading()
				const {
					data,
					statusCode
				} = res;
				// #ifndef HELPER-PROD	
				// #endif 
				if (statusCode >= 200 && statusCode < 300 && data != null) {
					if (data.code === 401) { // 会话过期,清除本地数据,跳登录
						uni.clearStorageSync();
						if (!uni.getStorageSync('token')) { // 避免多次跳转登录 
							uni.redirectTo({
								url: '/pages/login/login',
								complete(res) {
									console.log(res);
								}
							});
						}
						reject(data);
					} else if (data.code == 200) {
						resolve(data);

					} else if (['BASE.501', 'BASE.502', 'BASE.506', 'BASE.508', 'BASE.509',
							'BASE.511', 'BASE.512', 'BASE.012', 'BASE.002'
						].includes(data.code)) {
						reject(data);

					} else {
						reject(data);
						uni.showToast({
							'title': data.msg,
							'icon': 'none',
							'duration': 2200
						});
					}
				} else {
					const error = {
						retCode: '9999',
						retMsg: '请求失败'
					};
					reject(error);
				}
			},
			fail: (err) => {
				// #ifndef HELPER-PROD	 
				// #endif
				uni.hideLoading()
				const error = {
					retCode: '9999',
					retMsg: '网络异常，请检查网络设置'
				};
				uni.showToast({
					'title': '网络异常，请检查网络设置',
					'icon': 'none',
					'duration': 2200
				});
				reject(error);
			}
		});
	});
}


export default function(url, data, method = 'post', timeout = 30000) {
	return Request(url, data, method, timeout);
}